//
//  HGOrderDetailVC.m
//  RedWinMall
//
//  Created by HeDianZhao on 2018/8/1.
//  Copyright © 2018年 HeDianZhao. All rights reserved.
//

#import "HGOrderListVC.h"
#import "HGGoodsOderCell.h"
#import "HGGoodsModel.h"
#import "HGOderDetailVC.h"
#import "SelectedListModel.h"
#import "SelectedListView.h"
#import "HGLogisticsVC.h"
#import "PayViewModel.h"

@interface HGOrderListVC ()<UITableViewDataSource, UITableViewDelegate, HGPaymentCellDelegate>

@property (nonatomic,strong)UITableView* tableView;
//页面
@property (nonatomic,assign)NSInteger page;

@property (nonatomic,strong)NSMutableArray<NSArray <HGGoodsModel *> *>* goodOders;

@end

@implementation HGOrderListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initSubViews];
    
    [self initDatasWithType:_type];
}

#pragma mark -
- (void)initDatasWithType:(NSInteger)type {
    
    _page++;
    
    NSDictionary *parameters = @{
                                 @"state" : [NSNumber numberWithInteger:type],
                                 @"pageNum" : [NSNumber numberWithInteger:_page]
                                 };
    
    [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/order/list") parameters:parameters completion:^(LMJBaseResponse *response) {
        
        if (response.responseModel.status == 1) {
         
            if (_page != [response.responseModel.data[@"page"] integerValue]) {
                _tableView.mj_footer.state = MJRefreshStateNoMoreData;
                return;
            }
            NSArray<HGGoodsModel *> *goods = [HGGoodsModel mj_objectArrayWithKeyValuesArray:response.responseModel.data[@"rows"]];
            [goods enumerateObjectsUsingBlock:^(HGGoodsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSArray *arr = @[obj];
                [self.goodOders addObject:arr];
            }];
            
            [_tableView reloadData];
        }
        
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat sectionHeaderHeight = 10;//设置你footer高度
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    
}

- (void)initSubViews {
    [self.tableView registerClass:[HGGoodsOderCell class] forCellReuseIdentifier:@"HGGoodsOderCell"];
    [self.tableView registerClass:[HGPaymentCell class] forCellReuseIdentifier:@"HGPaymentCell"];
    [self.tableView registerClass:[HGPaymentBeenCell class] forCellReuseIdentifier:@"HGPaymentBeenCell"];
    [self.tableView registerClass:[HGCmpBeenCell class] forCellReuseIdentifier:@"HGCmpBeenCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger state = _goodOders[section].firstObject.state;
    NSInteger sendType = _goodOders[section].firstObject.sendState;
    return (state == 2 && sendType == 1) == YES ?  1 : 2;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _goodOders.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger state = _goodOders[indexPath.section].firstObject.state;
    NSInteger sendType = _goodOders[indexPath.section].firstObject.sendState;
    
    if (indexPath.row == 0) {
        HGGoodsOderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGGoodsOderCell"];
        cell.model = _goodOders[indexPath.section][indexPath.row];
        return cell;
    } else {
        if (state == 1) {
            HGPaymentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGPaymentCell"];
            cell.models = _goodOders[indexPath.section];
            cell.indexPath = indexPath;
            cell.delegate = self;
            return cell;
        } else if (state == 2 && sendType == 2) {
            HGPaymentBeenCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGPaymentBeenCell"];
            cell.models = _goodOders[indexPath.section];
            cell.indexPath = indexPath;
            cell.delegate = self;
            return cell;
        } else if (state == 3 || state == 4) {
            HGCmpBeenCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGCmpBeenCell"];
            cell.models = _goodOders[indexPath.section];
            cell.indexPath = indexPath;
            cell.delegate = self;
            cell.isDel = state == 3 ? YES : NO;
            return cell;
        }
        return [UITableViewCell new];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.row == 0 ? 135 : 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_goodOders == nil || _goodOders.count == 0 || indexPath.row == 1) return;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HGOderDetailVC *vc = [[HGOderDetailVC alloc] init];
    vc.goodsModel = _goodOders[indexPath.section][indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [UIView new];
    view.backgroundColor = kColorBackground;
    return view;
}


#pragma mark - 0.付款 1.取消订单 2.确认收货 3.查看物流 4.删除订单
- (void)tapAction:(NSInteger)type withModel:(HGGoodsModel *)model indexPath:(NSIndexPath *)indexPath {
    if (type == 1) {
        
        SelectedListView *view = [[SelectedListView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([[UIScreen mainScreen] bounds]), 0) style:UITableViewStylePlain];
        
        view.isSingle = YES;
        
        view.array = @[[[SelectedListModel alloc] initWithSid:0 Title:@"我不想买了"] ,
                       [[SelectedListModel alloc] initWithSid:1 Title:@"信息填错重新拍"] ,
                       [[SelectedListModel alloc] initWithSid:2 Title:@"卖家缺货"] ,
                       [[SelectedListModel alloc] initWithSid:3 Title:@"其他原因"] ,
                       ];
        
        view.selectedBlock = ^(NSArray<SelectedListModel *> *array) {
            
            [LEEAlert closeWithCompletionBlock:^{
                
                [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/order/pay/cancel") parameters:@{@"orderNo": [NSNumber numberWithLong:model.no]} completion:^(LMJBaseResponse *response) {
                    if (response.responseModel.status == 1) {
                        [[XNProgressHUD shared] showSuccessWithTitle:response.responseModel.message];
                        [_goodOders removeObjectAtIndex:indexPath.section];
                        [_tableView reloadData];
                    }
                }];
            }];
        };
        
        [LEEAlert actionsheet].config
        .LeeTitle(@"取消订单原因")
        .LeeItemInsets(UIEdgeInsetsMake(20, 0, 20, 0))
        .LeeAddCustomView(^(LEECustomView *custom) {
            
            custom.view = view;
            
            custom.isAutoWidth = YES;
        })
        .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
        .LeeAddAction(^(LEEAction *action) {
            
            action.title = @"取消";
            
            action.titleColor = [UIColor blackColor];
            
            action.backgroundColor = [UIColor whiteColor];
        })
        .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
        .LeeHeaderColor([UIColor colorWithRed:243/255.0f green:243/255.0f blue:243/255.0f alpha:1.0f])
        .LeeActionSheetBottomMargin(0.0f) // 设置底部距离屏幕的边距为0
        .LeeCornerRadius(0.0f)
        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
            // 这是最大宽度为屏幕宽度 (横屏和竖屏)
            return CGRectGetWidth([[UIScreen mainScreen] bounds]);
        })
        .LeeShow();
        return;
    }
    
    if (type == 4) {
        [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/order/del") parameters:@{@"orderId": [NSNumber numberWithLong:model.goodsId], @"state" : @0} completion:^(LMJBaseResponse *response) {
            if (response.responseModel.status == 1) {
                [[XNProgressHUD shared] showSuccessWithTitle:response.responseModel.message];
                [_goodOders removeObjectAtIndex:indexPath.section];
                [_tableView reloadData];
            }
        }];
        return;
    }
    
    if (type == 3) {
        [self.navigationController pushViewController:[[HGLogisticsVC alloc] initWithUrl:@"https://m.kuaidi100.com/index_all.html?type=quanfengkuaidi&postid=123456"] animated:YES];
        return;
    }
    
    if (type == 2) {
        [[XNProgressHUD shared] showLoadingWithTitle:@"收货中" maskType:(XNProgressHUDMaskTypeBlack)];
        [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/order/taked") parameters:@{@"orderNo" : [NSNumber numberWithLong:model.no]} completion:^(LMJBaseResponse *response) {
            [[XNProgressHUD shared] dismiss];
            if (response.responseModel.status == 1) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[XNProgressHUD shared] showSuccessWithTitle:response.responseModel.message];
                });
            }
        }];
        return;
    }
    
    if (type == 0) {
        
        HGPayView *view = [[HGPayView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 220) withMoeny:model.payAmount];
        
        [LEEAlert actionsheet].config
        .LeeAddCustomView(^(LEECustomView *custom) {
            
            custom.view = view;
            
            custom.isAutoWidth = YES;
        })
        .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
        .LeeAddAction(^(LEEAction *action) {
            
            action.title = @"去支付";
            action.titleColor = [UIColor whiteColor];
            action.backgroundColor = kColorMainTheme;
            action.height = 45.0f;
            action.clickBlock = ^{
              //支付
                NSLog(@"%ld",view.payType);
                [self payType:view.payType oderNo:@(model.no).description];
            };
        })
        .LeeHeaderInsets(UIEdgeInsetsMake(0, 0, 0, 0))
        .LeeActionSheetBottomMargin(0.0f)
        .LeeCornerRadius(0.0f)
        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
            
            // 这是最大宽度为屏幕宽度 (横屏和竖屏)
            
            return CGRectGetWidth([[UIScreen mainScreen] bounds]);
        })
        .LeeOpenAnimationConfig(^(void (^animatingBlock)(void), void (^animatedBlock)(void)) {
            
            [UIView animateWithDuration:1.0f delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:1 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                
                animatingBlock(); //调用动画中Block
                
            } completion:^(BOOL finished) {
                
                animatedBlock(); //调用动画结束Block
            }];
            
        })
        .LeeShow();
    }
}


- (void)payType:(NSInteger)type oderNo:(NSString *)oderNo {
    
    [[NSUserDefaults standardUserDefaults] setValue:oderNo forKey:@"oderNo"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/order/pay/param") parameters:@{@"orderNo" : oderNo,@"payWay" : [NSNumber numberWithInteger:type]} completion:^(LMJBaseResponse *response) {
        if (response.responseModel.status == 1) {
            if (type == 1) {
                [[PayViewModel sharePayService] AliPayWithSignature:response.responseModel.data[@"param"]];
                return;
            }
            NSData *jsonData = [response.responseModel.data[@"param"] dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *param = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
            PayModel *model = [PayModel new];
            [model setValuesForKeysWithDictionary:param];
            [[PayViewModel sharePayService] WeChatWithModel:model];
        }
    }];
}

- (UITableView *)tableView {
    if (!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = 10;
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _page = 0;
            [_goodOders removeAllObjects];
            [self initDatasWithType:_type];
        }];
        
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
             [self initDatasWithType:_type];
        }];
        
        [self.view addSubview:_tableView];
        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(44);
            make.bottom.left.right.equalTo(self.view);
        }];
    }
    return _tableView;
}

- (NSMutableArray<NSArray<HGGoodsModel *> *> *)goodOders {
    if (!_goodOders) {
        _goodOders = [@[] mutableCopy];
    }
    return _goodOders;
}

@end
